package com.caoheng.core.exceptions;

import com.caoheng.core.common.Result;
import com.caoheng.core.enums.ResultEnum;
import com.caoheng.core.util.ResultUtil;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;


@ControllerAdvice
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler {


    @ExceptionHandler(value = Throwable.class )
    public ResponseEntity<Result> errorForInternal(Throwable e){
        logger.error(String.format("业务异常,%s",e.getMessage()),e);
        return ResponseEntity.ok(ResultUtil.error(ResultEnum.ERROR_500));
    }

    @ExceptionHandler(value = IllegalArgumentException.class)
    public ResponseEntity errorForIllegalArgument(IllegalArgumentException e){
        logger.error(String.format("参数错误,%s",e.getMessage()),e);
        return ResponseEntity.ok(ResultUtil.error(ResultEnum.ERROR_400));
    }

    @Override
    protected ResponseEntity<Object> handleBindException(BindException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return handleForValidException(ex.getBindingResult(),status);
    }

    @Override
    protected ResponseEntity<Object> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatus status, WebRequest request) {
        return handleForValidException(ex.getBindingResult(),status);
    }

    private ResponseEntity handleForValidException(BindingResult result,HttpStatus status){
        StringBuilder messageBuilder = new StringBuilder();
        if(result != null){
            if(result.hasErrors()){
                for(ObjectError error : result.getAllErrors()){
                    messageBuilder.append(error.getDefaultMessage());
                }
            }
        }
        return new ResponseEntity(ResultUtil.error(status.value(),messageBuilder.toString()),HttpStatus.OK);
    }
}
